'use strict'

import {app, protocol, BrowserWindow, ipcMain} from 'electron'
import {createProtocol} from 'vue-cli-plugin-electron-builder/lib'

const isDevelopment = process.env.NODE_ENV !== 'production'
import download from './utils/download'
protocol.registerSchemesAsPrivileged([
    {scheme: 'app', privileges: {secure: true, standard: true, stream: true}}
])
export let win = null;
console.log(process.env.NODE_ENV)

//stream:true加载视频，否则白屏
async function createWindow() {
    win = new BrowserWindow({
        width: 1920,
        height: 1080,
        frame: false,
        fullscreen: true,
        useContentSize: false,
        // resizable: false,
        webPreferences: {
            nodeIntegration: true, // 使渲染进程拥有node环境
            webSecurity: false,
            devTools: true
        }
    })

    if (process.env.WEBPACK_DEV_SERVER_URL) {
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        win.loadURL('app://./index.html')
    }
    win.setAlwaysOnTop(true);//窗口置顶
}

app.setLoginItemSettings({openAtLogin: true})//开机自启动
//app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

function registerLocalVideoProtocol() {
    protocol.registerFileProtocol('local-video', (request, callback) => {
        const url = request.url.replace(/^local-video:\/\//, '')
        const path = require('path')
        // Decode URL to prevent errors when loading filenames with UTF-8 chars or chars like "#"
        const decodedUrl = decodeURI(url) // Needed in case URL contains spaces
        try {
            return callback(path.join(__static, decodedUrl))//这步是路径指向public目录
        } catch (error) {
            console.error(
                'ERROR: registerLocalVideoProtocol: Could not get file path:',
                error
            )
        }
    })
}


app.on('ready', async () => {
    await createWindow()
    registerLocalVideoProtocol()
})

ipcMain.on('open-devtools', (event, arg) => {
    win.webContents.openDevTools()
})

if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
